<template>
  <div class="material-top material-analysis bg-background text-foreground p-6">
    <div class="material-table">
      <h2 class="text-2xl font-bold mb-6">按应急物资库存统计</h2>
      <div class="material-search">
        <el-form :inline="true" :model="model" class="query-form-inline">
          <el-form-item class="query-form-item" label="物资类别：" label-position="top" prop="material_type">
            <el-select v-model="model.material_type" placeholder="请选择" @change="getMaterialAnalysisData" clearable>
              <el-option label="生活保障类" value="生活保障类" />
              <el-option label="生命救助类" value="生命救助类" />
              <el-option label="基层应急救援力量" value="动力燃料类" />
              <el-option label="通讯广播类" value="通讯广播类" />
              <el-option label="污染清理类" value="污染清理类" />
              <el-option label="个人防护类" value="个人防护类" />
              <el-option label="工程设备类" value="工程设备类" />
              <el-option label="医疗救护类" value="医疗救护类" />
              <el-option label="照明设备类" value="照明设备类" />
              <el-option label="交通运输类" value="交通运输类" />
              <el-option label="器材工具类" value="器材工具类" />
              <el-option label="侦检探测类" value="侦检探测类" />
              <el-option label="消防灭火类" value="消防灭火类" />
              <el-option label="生命支持类" value="生命支持类" />
              <el-option label="其他物资装备" value="其他物资装备" />
            </el-select>
          </el-form-item>
        </el-form>

      </div>
      <div class="material-table-box">
        <el-table ref="tableMaterialRef" v-loading="loading" :data="displayedMaterialData" style="width: 100%"
          align="center" class="data-table" @selection-change="handleSelectionMaterialChange"
          :header-cell-style="headerCellStyle" empty-text="暂无数据">
          <el-table-column label="序号" width="55" header-align="center" align="center">
            <template #default="scope">
              {{ startIndexMaterial + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="material_name" label="物资名称" header-align="center" align="center"></el-table-column>
          <el-table-column prop="material_type" label="物资分类" header-align="center" align="center"></el-table-column>
          <el-table-column prop="quantitys" label="库存总数" header-align="center" align="center"></el-table-column>
        </el-table>
        <div class="prev-box pagination bg-card text-card-foreground p-4 mt-4 flex items-center justify-between">
          <div>
            <p class="text-sm text-muted-foreground">
              一共检索到 <span class="font-medium total-num">{{ totalItemsMaterial }}</span> 条信息
            </p>
          </div>
          <div class="flex items-center space-x-2">
            <button @click="prevPageMaterial" :disabled="currentPageMaterial === 1" class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageMaterial === 1 }">
              上一页
            </button>
            <span class="text-sm text-muted-foreground">
              {{ currentPageMaterial }} / {{ totalPagesMaterial }}
            </span>
            <button @click="nextPageMaterial" :disabled="currentPageMaterial === totalPagesMaterial"
              class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPageMaterial === totalPagesMaterial }">
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="material-sector">
      <h2 class="text-2xl font-bold mb-6">应急物资分类占比分析</h2>
      <div ref="pieChartContainer" style="width: 100%; height: calc(100% - 56px);"></div>
    </div>
    <div class="material-bar">
      <h2 class="text-2xl font-bold mb-6">应急物资分类占比分析</h2>
      <div ref="barChartContainer" style="width: 100%; height: calc(100% - 56px);"></div>
    </div>
    <!-- <h2 class="text-2xl font-bold mb-6">物资分析</h2> -->

    <!-- 使用 v-if 来确保数据存在才渲染 -->
    <!-- <div v-if="materialData">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div v-for="(category, index) in materialData" :key="index"
          class="bg-card text-card-foreground p-4 rounded-lg shadow">
          <h3 class="text-lg font-semibold mb-2">{{ category?.name }}</h3>
          <ul>
            <li v-for="(item, itemIndex) in category?.items" :key="itemIndex" class="mb-2">
              <span class="font-medium">{{ item?.name }}:</span> {{ item?.quantity }} {{ item?.unit }}
            </li>
          </ul>
        </div>
      </div>
    </div> -->

    <!-- 如果数据不存在，显示加载信息 -->
    <!-- <div v-else class="text-center py-4">
      正在加载物资数据...
    </div> -->

    <!-- 物资使用趋势图表 -->
    <!-- <div class="mt-8">
      <h3 class="text-xl font-semibold mb-4">物资使用趋势</h3>
      <canvas ref="usageTrendChart"></canvas>
    </div> -->

    <!-- 物资库存状态 -->
    <!-- <div class="mt-8">
      <h3 class="text-xl font-semibold mb-4">物资库存状态</h3>
      <canvas ref="inventoryStatusChart"></canvas>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import Chart from 'chart.js/auto';
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/medical-resources-count'
})
const pieChartContainer = ref(null)
const barChartContainer = ref(null)
let pieChart = null
let barChart = null
const materialData = ref([]);
const selectedMaterialIds = ref([]);
const loading = ref(false);
const usageTrendChart = ref(null);
const inventoryStatusChart = ref(null);

const currentPageMaterial = ref(1)
const pageSizeMaterial = ref(5)
const totalItemsMaterial = computed(() => materialData.value.length)
const totalPagesMaterial = computed(() => Math.ceil(totalItemsMaterial.value / pageSizeMaterial.value))
const startIndexMaterial = computed(() => (currentPageMaterial.value - 1) * pageSizeMaterial.value)

const displayedMaterialData = computed(() => {
  const start = (currentPageMaterial.value - 1) * pageSizeMaterial.value
  const end = start + pageSizeMaterial.value
  return materialData.value.slice(start, end)
})
const getMaterialAnalysisData = async (value) => {
  model.value.material_type = value
  await searchMaterial()
}
const prevPageMaterial = () => {
  if (currentPageMaterial.value > 1) {
    currentPageMaterial.value--
  }
}

const nextPageMaterial = () => {
  if (currentPageMaterial.value < totalPagesMaterial.value) {
    currentPageMaterial.value++
  }
}
const searchMaterial = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/materials/count`, {
      params: model.value,
    })
    currentPageMaterial.value = 1
    materialData.value = response.data
    selectedMaterialIds.value = []
    loading.value = false

  } catch (error) {
    console.error('获取物资列表失败:', error)
    alert(
      '获取物资列表失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const pieData = ref([])
const barData = ref([])
const searchMaterialPie = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/type/count`)

    pieData.value = response.data

  } catch (error) {
    console.error('获取物资列表失败:', error)
    alert(
      '获取物资列表失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const searchMaterialBar = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/count/material`)
    barData.value = response.data

  } catch (error) {
    console.error('获取物资列表失败:', error)
    alert(
      '获取物资列表失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const handleSelectionMaterialChange = (selection) => {
  selectedMaterialIds.value = selection;
}
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
// 模拟异步数据获取
const fetchMaterialData = async () => {
  // 这里应该是实际的 API 调用
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        {
          name: '医疗物资',
          items: [
            { name: '口罩', quantity: 10000, unit: '个' },
            { name: '防护服', quantity: 500, unit: '套' },
            { name: '消毒液', quantity: 200, unit: '升' }
          ]
        },
        {
          name: '食品物资',
          items: [
            { name: '矿泉水', quantity: 5000, unit: '瓶' },
            { name: '方便面', quantity: 2000, unit: '箱' },
            { name: '压缩饼干', quantity: 1000, unit: '箱' }
          ]
        },
        {
          name: '救援设备',
          items: [
            { name: '救生衣', quantity: 100, unit: '件' },
            { name: '担架', quantity: 50, unit: '个' },
            { name: '救援绳', quantity: 200, unit: '米' }
          ]
        }
      ]);
    }, 1000);
  });
};
const model = ref({
  material_type: '生活保障类'
})
onMounted(async () => {
  await searchMaterial()
  await initUsageTrendChart()
  await initInventoryStatusChart()
});

const initUsageTrendChart = async () => {
  await searchMaterialPie()
  if (pieData.value.length) {
    pieChart = echarts.init(pieChartContainer.value)
    const data = pieData.value.map(item => ({
      value: item.percentage,
      name: item.material_type,
    }));

    const pieOption = {
      tooltip: {
        trigger: 'item',
        formatter: function (params) {
          // 自定义 tooltip 格式
          return `${params.name} ${params.value}%`;
        }
      },
      legend: {
        orient: 'horizontal',
        left: 'center',
        bottom: '0%',
        itemGap: 15,
        itemWidth: 15,
        itemHeight: 15,
        formatter: function (name) {
          return name;
        },
        textStyle: {
          // 设置图例文本样式
          fontSize: 12,
        },
        data: data.map(item => item.name),
      },
      series: [
        {
          name: data.map(item => item.name),
          type: 'pie',
          radius: '65%',
          center: ['50%', '40%'],
          // data: tadata,
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    pieChart.setOption(pieOption)
  }
};

const initInventoryStatusChart = async () => {
  await searchMaterialBar()
  if (barData.value.length) {
    barChart = echarts.init(barChartContainer.value)
    const data = barData.value.map(item => ({
      value: item.counts,
      name: item.department,
    }));

    const barOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        // formatter: `{b0}: <br />物资种类   {c0}`
      },
      grid: {
        top: '2%',
        left: '3%',
        right: '4%',
        bottom: '0%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            formatter: function (value) {
              // 根据字符长度进行换行
              const maxLength = 8; // 每行最多显示5个字符
              const lines = [];
              for (let i = 0; i < value.length; i += maxLength) {
                lines.push(value.substring(i, i + maxLength));
              }
              return lines.join('\n'); // 使用换行符连接
            },
            interval: 0 // 显示所有标签
          },
          data: data.map(item => item.name),
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '物资种类',
          type: 'bar',
          // barWidth: '50%',
          data: data
        }
      ]
    }
    barChart.setOption(barOption)
  }
};
</script>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

.box-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}
</style>

<style lass="scss" scoped>
.material-table {
  display: inline-block;
  width: 900px;
  /* height: 350px; */
  /* background: red; */
}

.query-form-item {
  width: 250px;
}

:deep(.query-form-item .el-form-item__label) {
  margin: 0;
  display: flex;
  align-items: center;
}

.material-table-box {
  width: 100%;
  height: 315px;
  position: relative;
}

.prev-box {
  width: 100%;
  position: absolute;
  bottom: 0;
}

.material-top {
  width: 100%;
  display: flex;
  /* align-items: center; */
  justify-content: space-between;
  flex-wrap: wrap;
  padding-bottom: 0;
}

.material-sector {
  width: calc(100% - 900px);
  height: 450px;
}

.material-bar {
  width: 100%;
  height: calc(100vh - 565px);
  flex: 0 0 100%;
}
</style>
